package com.group.itms.routes.activities;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.group.itms.routes.R;
import com.group.itms.routes.data.BObject;
import com.group.itms.routes.data.ObjectType;

public class TasksActivity extends BaseActivity {

	private ListView mListView;

	private BObject mObject;

	public static Intent getIntent(Context c, int objId) {
		Intent intent = new Intent(c, TasksActivity.class);
		intent.putExtra(OBJECT_ID, objId);
		return intent;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tasks);
		initObject();
		setTitle(mObject.getName());
		
		List<BObject> tasks;
		if (mObject.getType().equals(ObjectType.LOCATION)) {
			tasks = new ArrayList<BObject>();
			List<BObject> routes = mObject.getChildrenRoutes();
			for (BObject route : routes) {
				tasks.addAll(route.getChildrenTasks());
			}
		} else {
			tasks = mObject.getChildrenTasks();
		}

		mListView = (ListView) findViewById(R.id.lvTasks);
		mListView.setAdapter(new ArrayAdapter<BObject>(this,
				android.R.layout.simple_list_item_1, 0, tasks) {
			public View getView(int position, View convertView,
					android.view.ViewGroup parent) {
				View v = getLayoutInflater().inflate(R.layout.task_child_item,
						null);
				TextView tittle = (TextView) v.findViewById(R.id.tvTittle);
				TextView task = (TextView) v.findViewById(R.id.tvTask);

				tittle.setText(getItem(position).getName());
				task.setText(getItem(position).getText());

				return v;
			};
		});
	}

	private void initObject() {
		Bundle args = getIntent().getExtras();
		if (args == null) {
			throw new RuntimeException("TasksActivity does not have aruments");
		}
		int objId = args.getInt(OBJECT_ID, -1);

		if (objId == -1) {
			throw new RuntimeException("Missing args with key: " + OBJECT_ID
					+ " to activity: " + getClass());
		}
		mObject = getObject(objId);

		if (mObject == null) {
			throw new RuntimeException("Unable to find Location with id: "
					+ objId);
		}
	}

	@Override
	protected String getTag() {
		return TasksActivity.class.getSimpleName();
	}
}
